package com.kvest.bookprovider;

import android.content.Intent;
import android.widget.*;
import com.kvest.bookprovider.BookProviderMetaData.BookTableMetaData;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.Contacts.People;
import android.text.Layout;
import android.text.util.Linkify;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import java.util.Random;

public class BookActivity extends Activity 
{	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button button = new Button(this);
        button.setText("Test");
        
//        Button insert = new Button(this);
//        insert.setText("insert");
//        layout.addView(insert);
//        
//        Button delete = new Button(this);
//        delete.setText("delete");
//        layout.addView(delete);
//        
//        Button update = new Button(this);
//        update.setText("Update");
//        layout.addView(update);
//        
//        Button get = new Button(this);
//        get.setText("Get");
//        get.setOnClickListener(new View.OnClickListener() 
//        {
//			@Override
//			public void onClick(View v) 
//			{
//				 //TODO Auto-generated method stub
//			}
//		});
//        layout.addView(get);

        ListView listView = (ListView) findViewById(R.id.books_list_view);
        initListView(listView);
    }

    private void initListView(ListView listView) {

        String[] projection = new String[]{BookProviderMetaData.BookTableMetaData._ID, BookProviderMetaData.BookTableMetaData.BOOK_NAME, BookProviderMetaData.BookTableMetaData.BOOK_AUTHOR};
        Uri uri = BookProviderMetaData.BookTableMetaData.CONTENT_URI;
        Cursor cursor = managedQuery(uri, projection ,null,null,null);

        // формируем столбцы сопоставления
        String[] from = new String[] {BookProviderMetaData.BookTableMetaData.BOOK_NAME, BookProviderMetaData.BookTableMetaData.BOOK_AUTHOR};
        int[] to = new int[] { R.id.book_name, R.id.book_author };

        // создааем адаптер и настраиваем список
        SimpleCursorAdapter scAdapter = new SimpleCursorAdapter(this, R.layout.listitem, cursor, from, to);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(getApplicationContext(), "i=" + i + ", l=" + l, Toast.LENGTH_SHORT).show();
            }
        });
        listView.setAdapter(scAdapter);
    }
    
    public void insert() 
	{
		ContentValues values = new ContentValues();
        Random random  = new Random(System.currentTimeMillis());
        int id = random.nextInt();
		values.put(BookTableMetaData._ID,  Integer.toString(id));
		values.put(BookTableMetaData.BOOK_NAME, "Book" + id);
		values.put(BookTableMetaData.BOOK_AUTHOR,"Kvest" + id);
		
		ContentResolver resolver = getContentResolver();
		
		Uri uri = resolver.insert(BookTableMetaData.CONTENT_URI, values);
		Log.d("INSERT", uri.toString());
	}
    
    public void get() 
	{
//        Intent intent = new Intent(getApplicationContext(), BooksListActivity.class);
//        startActivity(intent);

		String[] projection = new String[]{BookTableMetaData._ID, BookTableMetaData.BOOK_NAME, BookTableMetaData.BOOK_AUTHOR};
		Uri uri = BookProviderMetaData.BookTableMetaData.CONTENT_URI;
		Cursor cur = managedQuery(uri, projection ,null,null,null);

		Log.d("Kvest",Integer.toString(cur.getColumnCount()));

        int nameIndex = cur.getColumnIndex(BookTableMetaData.BOOK_NAME);
		int index = cur.getColumnIndex(BookTableMetaData.BOOK_AUTHOR);
		for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext())
		{
			Log.d("Kvest", cur.getString(nameIndex) + "=" + cur.getString(index));
		}

	}

    public void delete()
    {
        int id = getRandomId();
        Log.d("Kvest", "idDel=" + id);

        ContentResolver resolver = getContentResolver();
        int deleted = resolver.delete(BookProviderMetaData.BookTableMetaData.CONTENT_URI, BookTableMetaData._ID + "=?",
                        new String[]{Integer.toString(id)});
        Log.d("Kvest", "deleted=" + deleted);
    }

    public void update()
    {
        int id = getRandomId();
        Log.d("Kvest", "idUpdate=" + id);

        ContentValues values = new ContentValues();
        Random random  = new Random();
        int newId = random.nextInt();
        values.put(BookTableMetaData._ID,  Integer.toString(id));
        values.put(BookTableMetaData.BOOK_NAME, "Book" + newId);
        values.put(BookTableMetaData.BOOK_AUTHOR,"newKvest" + newId);

        ContentResolver resolver = getContentResolver();
        int update = resolver.update(BookProviderMetaData.BookTableMetaData.CONTENT_URI, values , BookTableMetaData._ID + "=?",
                new String[]{Integer.toString(id)});
        Log.d("Kvest", "update=" + update);
    }

    private int getRandomId() {
        String[] projection = new String[]{BookTableMetaData._ID};
        Uri uri = BookProviderMetaData.BookTableMetaData.CONTENT_URI;
        Cursor cur = managedQuery(uri, projection ,null,null,null);
        int index = cur.getColumnIndex(BookTableMetaData._ID);

        cur.moveToFirst();

        if (!cur.isAfterLast()) {
            return cur.getInt(index);
        } else {
            return -1;
        }
    }

    public void clichobserver(View target)
    {
    	switch (target.getId()) 
    	{
			case R.id.get: get(); break;
			case R.id.insert: insert(); break;
            case R.id.delete: delete(); break;
            case R.id.update: update(); break;
		}
    }
}